import React, { useEffect } from "react"
import { useNavigate, useRoutes, useLocation } from "react-router-dom"


type route = {
    path: string,
    element: React.ReactNode
}
type Iroute = route & {
    children?: Array<route>
}

export type Iroutes = Array<Iroute>




//类型
type Iguard = (key: string, routes: Iroutes, storage?: string) => React.ReactNode

//重载window类型
declare global {
    interface Window {
        [k: string]: any
    }
}

// storage = 'sessionStorage'

// window['sessionStorage'].getItem()
/**
 * 
 * @param key {String} token对应存储在本地的key
 * @param routes {Iroutes} 路由的routes配置
 */

const useRoutesWithGuard: Iguard = (key, routes, storage = 'sessionStorage') => {
    // let token: string | null = sessionStorage.getItem(key)
    let token: string | null = window[storage].getItem(key)

    let navigate = useNavigate()

    let Element = useRoutes(routes)

    let location = useLocation()
    useEffect(() => {
        if (!token) {
            //没有token，跳转到login
            //如果访问的页面不是login 就跳转到login
            if (location.pathname !== "/login") {
                navigate('/login')
            }
        }
    })
    return Element
}
export default useRoutesWithGuard